﻿using CommonEntity;
using DataBaseCommon;
using Microsoft.AspNetCore.Mvc.RazorPages;
using MongoDB.Driver;
using NetCore6WebAPITestOneEntity;
using NetCore6WebAPITestOneRequestEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetCroe6WebAPITestOneResponse
{
    public class UserinfoMongoDbResponse
    {
        MongoDbClientScopedHelper _mongoDbClientHelper;

        public UserinfoMongoDbResponse(MongoDbClientScopedHelper mongoDbClientHelper)
        {
            _mongoDbClientHelper = mongoDbClientHelper;
        }

        public UserinfoMongodbModel InserUserinfo(UserinfoMongodbModel userinfo) {
            var c = _mongoDbClientHelper.GetDBCollection<UserinfoMongodbModel>("userinfo", "mongotest_db");
            c.InsertOne(userinfo);
            UserinfoMongodbModel u = c.Find<UserinfoMongodbModel>(item => item.UserID == userinfo.UserID).ToList<UserinfoMongodbModel>().FirstOrDefault();
            return u;
        }

        public UserinfoMongodbModel GetUserinfo(string userid)
        {
            var c = _mongoDbClientHelper.GetDBCollection<UserinfoMongodbModel>("userinfo", "mongotest_db");
            UserinfoMongodbModel u = c.Find<UserinfoMongodbModel>(item => item.UserID == userid).ToList<UserinfoMongodbModel>().FirstOrDefault();
            return u;
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public Page<UserinfoMongodbModel> GetUserinfoPage(UserinfoMongodbPageRequestViewModel para)
        {
            var c = _mongoDbClientHelper.GetDBCollection<UserinfoMongodbModel>("userinfo", "mongotest_db");
            FilterDefinitionBuilder<UserinfoMongodbModel> builderFilter = Builders<UserinfoMongodbModel>.Filter;

            List<FilterDefinition<UserinfoMongodbModel>> queryList = new List<FilterDefinition<UserinfoMongodbModel>>();
            if (!string.IsNullOrEmpty(para.UserName))
            {
                queryList.Add(builderFilter.Where(item => item.UserName==para.UserName));
            }
            queryList.Add(builderFilter.Where(item => item.IsValid == 1));

            //排序
            SortDefinitionBuilder<UserinfoMongodbModel> sortBuilder = new SortDefinitionBuilder<UserinfoMongodbModel>();
            List<SortDefinition<UserinfoMongodbModel>> sortList = new List<SortDefinition<UserinfoMongodbModel>>();
            sortList.Add(sortBuilder.Descending(item => item.CreateTime));

            if (!string.IsNullOrEmpty(para.query))
            {
                queryList.Add(builderFilter.Where(item => item.UserName.Contains(para.query) || item.UserEmail.Contains(para.query)));
            }

            return _mongoDbClientHelper.GetPage<UserinfoMongodbModel>(20, 1, builderFilter.And(queryList), c);
        }
    }
}
